<template>
  <div>
    <b-table
      ref="table"
      :out-loading="loading"
      :columns="columns"
      :scroll="{ x: 1300 }"
      :request="loadData"
      :export-config="{ use: true, select: '钢筋需用总计划导出选中', all: '钢筋需用总计划导出全部' }"
    >
      <template
        v-if="state !== 3"
        slot="prefix"
        slot-scope="ref"
      >
        <a-button
          type="primary"
          icon="plus"
          :loading="loadingData.add"
          @click="addRow('add')"
        >
          添加行
        </a-button>
        <a-button
          type="danger"
          icon="delete"
          @click="ref.delete(delFun)"
        >
          删除行
        </a-button>
      </template>
      <template
        v-if="state !== 3"
        slot="suffix"
      >
        <a-button
          type="primary"
          icon="download"
          :loading="loadingData.download"
          @click="addRow('download')"
        >
          标准模板下载
        </a-button>
        <!-- 导入 -->
        <ExcelImportButton
          ref="excelImportButton"
          icon="import"
          class="ml12"
          @handleSubmit="handleSubmit"
        />
      </template>
      <span slot="index" slot-scope="text, record, index">{{ index + 1 }}</span>
      <template
        v-for="col in [
          'materialName',
          'constructionSiteStr',
          'constructionTypeStr',
          'constructionLevelStr',
          'materialCode',
          'rebarModel',
          'rebarNum',
          'remark'
        ]"
        :slot="col"
        slot-scope="text, record"
      >
        <div
          :key="col"
          class="form-item"
        >
          <template v-if="state !== 3">
            <BaseInput
              v-if="col === 'materialName'"
              v-model="record.materialName"
              v-check="col"
              disabled
            />
            <a-select
              v-else-if="col === 'constructionSiteStr'"
              v-model="record.constructionSite"
              v-check="'constructionSite'"
              placeholder="请选择"
              style="border-color: #e4ac0b; background-color: #fff9e8; margin: -5px 0; width: 100%"
              @blur="save(record)"
            >
              <a-select-option v-for="item in partArr" :key="item.id" :value="item.id">{{ item.name }}
              </a-select-option>
            </a-select>
            <a-select
              v-else-if="col === 'constructionTypeStr'"
              v-model="record.constructionType"
              v-check="'constructionType'"
              placeholder="请选择"
              style="'border-color: #e4ac0b; background-color: #fff9e8; margin: -5px 0; width: 100%'"
              @blur="save(record)"
            >
              <a-select-option v-for="item in typeArr" :key="item.id" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
            <a-select
              v-else-if="col === 'constructionLevelStr'"
              v-model="record.constructionLevel"
              v-check="'constructionLevel'"
              placeholder="请选择"
              style="'border-color: #e4ac0b; background-color: #fff9e8; margin: -5px 0; width: 100%'"
              @blur="save(record)"
            >
              <a-select-option v-for="item in levelArr" :key="item.id" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
            <BaseInput
              v-else-if="col === 'materialCode'"
              v-model="record.materialCode"
              v-check="col"
              disabled
            />
            <!-- <BaseInput
                           v-else-if="col==='materialName'"
                            v-model="record.materialName"
                            v-check="col"
                            disabled
                        /> -->
            <BaseInput
              v-else-if="col === 'rebarModel'"
              v-model="record.rebarModel"
              v-check="col"
              style="'border-color: #e4ac0b; background-color: #fff9e8; margin: -5px 0; width: 100%'"
              disabled
            />
            <BaseInput
              v-else-if="col === 'remark'"
              v-model="record[col]"
              v-check="col"
              class="remark"
              placeholder="请输入"
              @blur="save(record)"
            />
            <BaseInputNumber
              v-else-if="col === 'rebarNum'"
              v-model="record[col]"
              v-check="col"
              style="'border-color: #e4ac0b; background-color: #fff9e8; margin: -5px 0; width: 100%'"
              :precision="3"
              placeholder="请输入"
              @blur="save(record)"
            />
            <BaseInputNumber
              v-else
              v-model="record[col]"
              v-check="col"
              style="'border-color: #e4ac0b; background-color: #fff9e8; margin: -5px 0; width: 100%'"
              :precision="2"
              placeholder="请输入"
              @blur="save(record)"
            />
          </template>
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
    </b-table>
    <materialListAndDir
      ref="detailDialog"
      @createList="createList"
    />
  </div>
</template>
<script>
import {
    totalPlanReinforcedList,
    totalPlanReinforcedListDel,
    totalPlanReinforcedListAdd,
    totalPlanReinforcedListEdit,
    downloadExcel
} from '@/api/material/materialMasterPlan/materialPlan'
import { rebarColums } from './insideModel'
import { selectOption } from '@/api/material/goods/goods'
import materialListAndDir from '@/components/materialListAndDir/materialListAndDir'

const data = []
export default {
    name: 'RebarPlan',
    components: {
        materialListAndDir
    },
    props: {
        state: {
            type: Number
        },
        id: {
            type: String
        }
    },
    data() {
        return {
            loading: false,
            loadData: (params) => {
                return totalPlanReinforcedList({ ...params, id: this.id })
            },
            delFun: totalPlanReinforcedListDel,
            downloadExcel: downloadExcel,
            columns: rebarColums,
            partArr: [],
            levelArr: [],
            typeArr: [],
            loadingData: {
                add: false,
                download: false
            },
            rules: {
                constructionSite: { rule: 'required', message: '施工部位不能为空' },
                constructionType: { rule: 'required', message: '构件类型不能为空' },
                constructionLevel: { rule: 'required', message: '钢筋级别不能为空' },
                materialCode: { rule: 'required', message: '物料编码不能为空' },
                rebarNum: { rule: 'required', message: '钢筋量不能为空' }
            },
            editingIndex: null,
            checkKeys: new Map(),
            importCheck: {
                物资名称: 'materialName',
                物料编码: 'materialCode',
                钢筋规格: 'rebarModel',
                施工部位: 'constructionSiteStr',
                构件类型: 'constructionTypeStr',
                钢筋级别: 'constructionLevelStr',
                钢筋量: 'rebarNum',
                备注: 'remark'
            } // 导入字段对应
        }
    },
    directives: {
        check: {
            inserted(el, binding, vNode) {
                if (vNode.context.rules[binding.value]) {
                    let rule = vNode.context.rules[binding.value]
                    vNode.context.checkKeys.set(binding.value, rule.message)
                }
            }
        }
    },
    mounted: function () {
        this.initData()
    },
    methods: {
        async initData() {
            this.loading = true
            await this.getPart()
            await this.getLevel()
            await this.getType()
            this.loading = false
        },

        onSearch(val) {
            this.$refs.detailDialog.open()
        },
        createList(data) {
            console.log(data)
            this.loading = true
            let params = []
            data.forEach((item) => {
                params.push({
                    constructionSite: null,
                    rebarModel: item.specificationModel,
                    materialCode: item.code,
                    materialName: item.name,
                    rebarNum: '',
                    remark: '',
                    constructionType: null,
                    editable: true,
                    projectId: this.id,
                    materialId: item.id,
                    constructionSiteStr: '',
                    constructionTypeStr: '',
                    constructionLevelStr: ''
                })
            })
            totalPlanReinforcedListAdd(params).then((res) => {
                if (res.code === 200) {
                    this.loading = false
                    this.$refs.table.getData(null, true)
                }
            })
        },
        async getPart() {
            let res = await selectOption({ type: 3 })
            if (res.code === 200) this.partArr = res.data
        },
        async getLevel() {
            let res = await selectOption({ type: 2 })
            if (res.code === 200) this.levelArr = res.data
        },
        async getType() {
            let res = await selectOption({ type: 4 })
            if (res.code === 200) this.typeArr = res.data
        },

        async addRow(type) {
            let temp = []
            if (this.$refs.table.totalSize !== 0) {
                this.loadingData[type] = true
                let res = await totalPlanReinforcedList({
                    pageSize: this.$refs.table.totalSize,
                    pageNo: 1,
                    id: this.id
                })
                this.loadingData[type] = false
                temp = res.data
            }
            if (type === 'add') {
                this.$refs.detailDialog.open(temp)
            } else {
                this.$refs.detailDialog.download(temp, this.downloadExcel, { type: 1 })
            }
        },
        async save(row) {
          if (row.constructionSite){
            let res = this.partArr.find(v=> v.id === row.constructionSite)
            if (res) row.constructionSiteStr = res.name
          }
          if (row.constructionType){
            let res = this.typeArr.find(v=> v.id === row.constructionType)
            if (res) row.constructionTypeStr = res.name
          }
          if (row.constructionLevel){
            let res = this.levelArr.find(v=> v.id === row.constructionLevel)
            if (res) row.constructionLevelStr = res.name
          }

            await totalPlanReinforcedListEdit(row)
        },
        /**
         * 导入记录
         */
        handleSubmit(e) {
            let form = []
            console.log(e)
            for (let index in e) {
                form.push({})
                let keys = e[index]
                let listItem = form[index]
                // 校验excel的表头数量
                // if (Object.keys(keys)?.length === 7) {
                // 校验excel的表头字段
                for (let i in this.importCheck) {
                    let item = this.importCheck[i]
                    if (!Object.keys(keys).includes(i) && i == '钢筋量') {
                        this.$message.warning(`${i}必填`)
                        return
                    } else {
                        listItem[item] = keys[i]
                        if (item == 'rebarNum') {
                            if (isNaN(parseInt(listItem[item]))) {
                                this.$message.warning(`${i}必须为数字`)
                                return
                            }
                        }
                        listItem.projectId = this.id
                    }
                }
                // } else {
                //     this.$message.warning('数据不完整')
                //     return
                // }
            }
            this.loading = true
            totalPlanReinforcedListAdd(form).then(
                (res) => {
                    console.log(res)
                    this.$message.success('导入成功')
                    this.loading = false
                    this.$refs.table.getData(null, true)
                },
                (error) => {
                    console.log(error)
                    const errors = error.data.message.split('/')
                    if (errors.length > 0) {
                        this.$info({
                            title: '提示',
                            width: '650px',
                            content: function () {
                                return errors.map((i, index) => (
                                    <p style="margin-bottom: 10px;">
                                        {index + 1 > 2 ? index - 1 + ':' : ''}
                                        {i}
                                    </p>
                                ))
                            },
                            onOk() {}
                        })
                    }

                    this.loading = false
                }
            )
        }
    }
}
</script>
<style lang="less" scoped>
/deep/ .form-item  {
    .ant-input:not([disabled]),
    .ant-select:not(.ant-select-disabled) .ant-select-selection,
    .ant-calendar-picker-input,
    .ant-input-number-input,
    .ant-cascader-picker {
        border-color: #e4ac0b;
        background-color: #fff9e8;
    }
    .remark {
        .ant-input {
            border-color: inherit;
            background-color: initial;
        }
    }
}
</style>
